<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-button type="primary" icon="plus" @click="handleCreate">新增</el-button>
        <el-button type="primary" icon="search" @click="getList">查询</el-button>
      </div>

      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
        <el-table-column label="主机名称" prop="hostname" />
        <el-table-column label="外网IP" prop="publicIp" />
        <el-table-column label="内网IP" prop="localIp" />
        <el-table-column label="SSH端口" prop="port" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="handleUpdate(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" @click="handleCertAuth(row)">证书认证</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        v-model:page="listQuery.page"
        v-model:limit="listQuery.limit"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <HostDialog v-model="dialogVisible" :host="tempHost" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup name="Host">
import { reactive, ref } from "vue";
import { deleteHost, getHostList, Host } from "@/api/res/host-api";
import HostDialog from "./components/HostDialog.vue";
import Pagination from "@/components/Pagination/index.vue";

const listLoading = ref(false);
const list = ref(Array<Host>());
const total = ref(0);
const listQuery = reactive({
  page: 1,
  limit: 10,
});

const dialogVisible = ref(false);
const certAuthVisible = ref(false);
const currentHostId = ref(null);
let tempHost = reactive({});

const getList = async () => {
  listLoading.value = true;
  try {
    const res = await getHostList(listQuery);
    list.value = res.list;
    total.value = res.total;
  } finally {
    listLoading.value = false;
  }
};

const handleCreate = () => {
  Object.assign(tempHost, {
    id: undefined,
    hostname: "",
    publicIp: "",
    localIp: "",
    port: 22,
    username: "",
    password: "",
  });
  dialogVisible.value = true;
};

const handleUpdate = (row: any) => {
  //Object.assign(tempHost, row);
  tempHost = row;
  dialogVisible.value = true;
};

const handleDelete = async (row) => {
  try {
    await deleteHost(row.id);
    await getList();
  } catch (error) {
    console.error("删除失败:", error);
  }
};

const handleCertAuth = (row) => {
  currentHostId.value = row.id;
  certAuthVisible.value = true;
};

const handleSuccess = () => {
  dialogVisible.value = false;
  getList();
};

getList();
</script>
